import { reqGetCode, reqUserRegister,reqUserLogin,reqUserInfo,reqLogOut} from '@/api';
import {setToken, getToken,removeToken} from '@/utils/token';
//登录与注册模块
const state = {
    code: '',//验证码
    token:getToken(),
    //token:localStorage.getItem('TOKEN'),//标识
    userInfo:{},//用户信息
};
const mutations = {
    //修改获取验证码 
    GETCODE(state, code) {
        state.code = code;
    },
    //修改token 
    USERLOGIN(state,token){
        state.token = token;
    },
    //修改用户信息
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo;
    },
    //请求本地数据
    GETLOGOUT(state){
        state.token ='';
        state.userInfo = {};
        removeToken();//本地存储数据清空
    }
};
const actions = {
    //获取验证码 
    async getCode({ commit }, phone) {
        //获取验证码的这个接口：把验证码返回，但是正常情况，后台把验证码发到用户手机上【省钱】
        let result = await reqGetCode(phone);
        if (result.code == 200) {
            commit("GETCODE", result.data);
            return "ok";
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    //用户注册
    async userRegister({commit}, user){
        let result = await reqUserRegister(user);
        if(result.code == 200){
            console.log(result)
            return "ok";
        }else{
            return "失败";
        }
    },
    //登录业务
    async UserLogin({commit}, data){
        let result = await reqUserLogin(data);
        //将服务器下发 token,用户唯一标识(uuid)
        //将来经常通过带token找服务器要用户信息进行展示
        console.log(result)
        if(result.code == 200){
            commit("USERLOGIN",result.data.token);
            //持久化存储 token
            setToken(result.data.token);
            return "ok";
        }else{
            return "失败";
        }
    },
    //获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo();
        console.log(result)
        if(result.code == 200){
            //提交用户信息
            commit("GETUSERINFO",result.data);
            return "ok";
        }else{
            return "失败";
        }
        // 
    },
    //退出登录 
    async getLogout({commit}){
        //只是向服务器发起一次请求，通知服务器清除 token
       let result = await reqLogOut();
      //action 里面不能操作state,提交mutations修改state
       if(result.code == 200){
        commit('GETLOGOUT');
        return "ok";
       }else{
        return Promise.reject(new Error('faile'));

       }
    }


};
const getters = {};

export default {
    state,
    mutations,
    actions,
    getters
}